package com.googlecode.cswish.view;

import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.components.ClosingUIBean;

import com.googlecode.cswish.model.ElementList;
import com.googlecode.cswish.model.PageElement;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.util.FrameConstant;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * Call template "elements" to show each element
 * 
 * @author Jerry.Feng Date: 2008-5-30
 */
public class Elements extends ClosingUIBean {
	private static final Log logger = LogFactory.getLog(Elements.class);
	
	final public static String OPEN_TEMPLATE = "elements";
	final public static String TEMPLATE = "elements-close";
	
    public Elements(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
        super(stack, request, response);
    }
    
    @Override
	public String getDefaultOpenTemplate() {
		return OPEN_TEMPLATE;
	}
    
	@Override
	protected String getDefaultTemplate() {
		return TEMPLATE;
	}
	
	@Override
	public void evaluateExtraParams() {
		// name
		addParameter("name", name == null ? "" : name);
		
		PageElement ps = (PageElements) stack.getContext().get(FrameConstant.STACK_PAGEELEMENTS);
		if (ps != null && ps instanceof PageElements) {
			// Update the new PageStructure for the children
			PageElements defaultUISetting = (PageElements) ps;
			// Prepare the child elements
			addParameter("hiddenElements", defaultUISetting.getHiddenElements());
			addParameter("visibleElements", defaultUISetting.getVisibleElements());
			addParameter("columnCount", defaultUISetting.getColumnCount());
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("can't find element in PageElements:" + name + ", only use current input parameter");
			}
			
			ElementList list = new ElementList(new ArrayList(0), 1);
			Map parameters = getParameters();
			if (!parameters.containsKey("hiddenElements")) {
				addParameter("hiddenElements", list);
			}
			if (!parameters.containsKey("visibleElements")) {
				addParameter("visibleElements", list);
			}
			if (!parameters.containsKey("columnCount")) {
				addParameter("columnCount", 1);
			}
		}
	}
}